package util.c3p0;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mysql.jdbc.Statement;

/**
 * 
 * @author Chauncy
 *	创建C3P0Utils类，定义获取connection、释放connection的方法
 */

public class C3p0Utils {
	private static ThreadLocal<Connection> tl = new ThreadLocal();
	static ComboPooledDataSource dataSource = null;
	static {

		dataSource = new ComboPooledDataSource();
	}

	public static DataSource getDataSource() {
		return dataSource;
	}

	public static Connection getConnection(){
		Connection connection = (Connection)tl.get();
		if (connection == null) {
			try {
				connection = dataSource.getConnection();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		tl.set(connection);
		return connection;
	}

	public static void startTransaction(){
		Connection conn = getConnection();
		try {
			conn.setAutoCommit(false);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static void rollback(){
		Connection conn = getConnection();
		try {
			conn.rollback();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static void commit(){
		Connection conn = getConnection();
		try {
			conn.commit();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	// 释放资源
	public static void releaseConnection() {
		try {
			release(getConnection());
			tl.remove();
		} catch (Exception e) {
			// TODO: handle exception
		}
	
		
	}
	public static void release(Connection conn, ResultSet rs, Statement st) {
		closeRs(rs);
		closeSt(st);
		closeConn(conn);
	}
	
	public static void release(ResultSet rs, Statement st) throws Exception {
		closeRs(rs);
		closeSt(st);
		releaseConnection();
	}
	public static void release(Statement st) throws Exception {
		closeSt(st);
		releaseConnection();
	}
	public static void release(ResultSet rs) throws Exception {
		closeRs(rs);
		releaseConnection();
	}

	public static void release(Connection conn, ResultSet rs) {
		closeRs(rs);
		closeConn(conn);
	}

	public static void release(Connection conn, Statement st) {
		closeSt(st);
		closeConn(conn);
	}
	public static void release(Connection conn) {
		closeConn(conn);
	}

	private static void closeRs(ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				rs = null;
			}
		}
	}

	private static void closeSt(Statement st) {
		if (st != null) {
			try {
				st.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				st = null;
			}
		}
	}

	private static void closeConn(Connection conn) {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				conn = null;
			}
		}
	}

}

